const fs = require('fs')
const path = require('path')
const express = require('express')
const {
	Worker,
	isMainThread,
	MessagePort
} = require("worker_threads")

const app = express()

const port = 4080
const countJs = require("./public/common/count")

var files = []
var count = countJs()
var nowWorkerNum = 0
var maxWorkerNum = 2

app.use(express.static('public'))

var router = express.Router()
const getFileList = () => {

	if (isMainThread) {
		console.log("主线程")
	}

	fs.readdir('./public/json', (err, fileList) => {
		files = fileList
		while (nowWorkerNum <= maxWorkerNum) {
			findFile()
		}
	})
}

getFileList()

const findFile = () => {
	let index = count.add()
	if (nowWorkerNum > maxWorkerNum || index >= files.length) {
		// console.log(nowWorkerNum, nowIndex, files.length)
		return
	}

	const worker = new Worker("./public/workerJs/one.js")
	// 配置文件夹/文件路径
	let fileFoldPath = path.join(__dirname, 'public', 'Json')
	let filePath = path.join(fileFoldPath, files[index])
	// 创建Woker对象, 引入对应文件
	let data = {
		fileFoldPath,
		filePath,
		file: files[index]
	}

	// 向子线程发生消息
	worker.postMessage([data])
	nowWorkerNum++

	worker.on("message", (res) => {
		nowWorkerNum--
		if (count.check() <= files.length) {
			findFile()
		}
	})
}

router.get('/findFile', function(req, res) {
	res.send()
})

app.use('/mock', router)

app.listen(port, function() {
	console.log(port + '开启成功')
})
